package database

import (
	"log"

	"database/sql"
	_ "github.com/go-sql-driver/mysql"
)

type mysql struct {
	Url string
	db  *sql.DB
}

func MySql(url string) mysql {
	t := mysql{}
	t.Url = url
	return t
}

func (m *mysql) Open() bool {
	db, err := sql.Open("mysql", m.Url)
	if err != nil {
		log.Println("Open:", err.Error())
		return false
	}
	m.db = db
	return true
}

func (m *mysql) Close() {
	m.db.Close()
}

func (m *mysql) GetPassword(name string) (string, error) {
	err := m.db.Ping()
	if err != nil {
		return "", err
	}

	var pwd string
	err = m.db.QueryRow(`select Upwd from User where Uname = ?`, name).Scan(&pwd)
	if err != nil {
		return "", err
	}
	return pwd, nil
}

func (m *mysql) GetAuthority(name string) (int, error) {
	err := m.db.Ping()
	if err != nil {
		return -1, err
	}

	var code int
	err = m.db.QueryRow(`select Ucode from User where Uname = ?`, name).Scan(&code)
	if err != nil {
		return -1, err
	}
	return code, nil
}
